using Digitalmes.Infrastructure.Scada.Handlers;
using ThingsEdge.Exchange.Forwarders;

namespace Digitalmes.Infrastructure.Scada.Forwarders;

/// <summary>
/// 通知消息处理。
/// </summary>
internal sealed class NativeNoticeForwarder(IServiceProvider serviceProvider, ILogger<NativeNoticeForwarder> logger) : INoticeForwarder
{
    /// <summary>
    /// 单一信号点。进/出站、扫码登只允许存在唯一的信号点。
    /// </summary>
    private static readonly Dictionary<string, Type> _singleHandlerMap = new()
    {
        { TagDefinition.PLC_Equipment_Alarm, typeof(EquipmentAlarmHandler) }, // 区域/工位警报
        //{ TagDefinition.PLC_Equipment_State, typeof(EquipmentAlarmHandler) },
        //{ TagDefinition.PLC_Equipment_Mode, typeof(EquipmentAlarmHandler) },
        //{ TagDefinition.PLC_Workstation_State, typeof(EquipmentAlarmHandler) }, // 工位运行状态（考虑安灯管理）
    }; 

    public async Task ReceiveAsync(NoticeContext context, CancellationToken cancellationToken = default)
    {
        var self = context.Message.Self();

        // 区域/工位警报
        if (_singleHandlerMap.TryGetValue(self.TagName, out var type))
        {
            var handler = (IScadaTellHandler)serviceProvider.GetRequiredService(type);
            await handler.HandleAsync(context, cancellationToken);
        }
        else
        {
            logger.LogWarning("通知的标记名称 {TagName} 必须属于 {@Tags} 其中的一种。", self.TagName, _singleHandlerMap.Keys);
        }
    }
}
